﻿
#include <iostream>
#include <boost/asio.hpp>
#include <string>
using std::string;
using std::cout;
using std::endl;
using std::cin;
using std::cerr;
const int MAX_SIZE = 1024;
int main()
{
    try {
        string rawIpAddress = "192.168.100.87";
        unsigned int port_num = 5555;
        //构造endpoint
        boost::asio::ip::tcp::endpoint ep(boost::asio::ip::
            address::from_string(rawIpAddress), port_num);
        //创建服务上下文
        boost::asio::io_context ioc;
        //创建socket（第二个参数可写，也可不写）
        boost::asio::ip::tcp::socket sock(ioc, ep.protocol());
        boost::system::error_code ec = boost::asio::error::host_not_found;
        //连接对端ip
        sock.connect(ep, ec);
        if (ec) {
            cerr << "sock connect error。"
                << "error code is: " << ec.value()
                << " message is: " << ec.message() << endl;
            return EXIT_FAILURE;
        }
        char buff[MAX_SIZE];
        while (1) {
            cin.getline(buff, MAX_SIZE);
            size_t length = strlen(buff);
            int s = sock.send(boost::asio::buffer(buff, length));
            if (s <= 0) {//对端关闭或者socket出现系统级错误
                cerr << "send error" << endl;
                return EXIT_FAILURE;
            }
            cout << "cli send success!" << endl;
            memset(buff, 0, MAX_SIZE);
            size_t reply = boost::asio::read(sock, boost::asio
                ::buffer(buff, length));
            if (reply <= 0) {
                cerr << "read error" << endl;
                return EXIT_FAILURE;
            }
            cout << "cli received message: " << buff << endl;
        }
    }
    catch (boost::system::system_error& e) {
        cerr << "system_error" << e.what() << endl;
    }  
    return EXIT_SUCCESS;
}

